/**
 * 申请单填加
 * @author hongwei 2018-09-07
 */
(function (window) {
    'use strict';
    var applyAdd = function (params) {
        $.extend(this.params, params);
        var that = this;
        that._init();   //初始化操作
    };
    applyAdd.prototype = {
        params : {
            data1 : []      //出行人数据
            ,data2 : []     //审批人数据
            ,ids  : []
            ,approve_ids : []
        }
        //初始化操作
        ,_init :function () {
            var that = this;
            that.getAddApplyInfo();             //step01:获取新增出差申请单数据，包含step06,step08
            that.selectCity();                  //step02:出差始发地 - 选择单个城市
            that.listenTravelSite();            //step03:获取点击单个城市收到发送监听事件
            that.selectCityMany();              //step04:出差目的地 - 选择多个城市
            that.dateClick();                   //step05:点击日期操作-出差开始时间和结束时间
            //that.picker1Select();             //step06:选择出行人
            that.delTravelPersonAddEvent();     //step07:删除出行人
            //that.picker2Select();             //step08:选择审批人
            that.delApprovePersonAddEvent();    //step09:删除审批人
            that.submitApply();                 //step10:提交申请单数据，包括step11
            //that.submitValidate();            //step11:提交参数验证
            that.resetForm();                   //step12:重置
            that.uploadImg();                   //step13:上传图片
            that.imageDelete();                 //step18:图片删除操作
        }

        //step01:获取新增出差申请单数据，
        , getAddApplyInfo : function () {
            var that = this;

            var param = {};
            param.url = Config.travel.getAddApplyInfo;
            //请求申请单列表接口
            ajax(param, function(ret) {
                // console.log(JSON.stringify(ret.data.passengerList));
                if (ret.code === 1) {
                    $("#book_user").val(ret.data.book_user_name);
                    //（一）出行人
                    that.createList(ret.data.passengerList, that.params.data1); //step1:出行人数据填充
                    delete ret.data.passengerList[$api.getStorage('user_id')];  //step2:审批人中删除当前登录人
                    that.picker1Select();
                    //（二）审批人
                    that.createList(ret.data.passengerList, that.params.data2); //step3:审批人数据填充
                    that.picker2Select();   //赋值
                } else {
                    $toast(ret.msg);
                }
            })
        }

        //step02:出差始发地 - 选择单个城市
        , selectCity : function () {
            $('#selectCity').click(function () {
                api.openWin({
                    name: 'select_city_single_win',
                    url: 'select_city_single_win.html',
                    slidBackEnabled: false
                });
            });
        }

        //step03:获取点击单个城市收到发送监听事件
        , listenTravelSite :function () {
            api.addEventListener({
                name: 'travelSite'
            }, function(ret, err) {
                $('#travel_site').val(ret.value.cname);
            });
            api.addEventListener({
                name: 'travelDestination'
            }, function(ret, err) {
                $('#travel_destination').val(ret.value.cname);
            });
        }

        //step04:出差目的地 - 选择多个城市
        ,selectCityMany : function () {
            $('#selectCityMany').click(function () {
                api.openWin({
                    name: 'select_city_many_win',
                    url: 'select_city_many_win.html',
                    slidBackEnabled: false
                });
            });
        }

        //step05:点击日期操作-出差开始时间和结束时间
        , dateClick : function () {
            var that = this;
            $('#my-endDate,#my-startDate').click(function(e) {
                var _this = $(this);
                var time = that.getNowFormatDate();
                var minDate = time;
                var stratTime = $('#my-startDate').val();
                if (_this.val()) time = _this.val();
                if (_this.attr('id') === 'my-endDate' && stratTime) minDate = stratTime;
                api.openPicker({
                    type: 'date',
                    date: time,
                    minDate: minDate,
                    title: '选择时间'
                }, function(ret, err) {
                    // console.log(JSON.stringify(ret));
                    ret.month = ret.month < 10 ? "0" + ret.month : ret.month;
                    ret.day   = ret.day < 10 ? "0" + ret.day : ret.day;
                    if (_this.attr('id') === 'my-endDate') {
                        //if(date1 > date2) return false;
                        // console.log($('#my-startDate').val());
                        // console.log(ret.year + "-" + ret.month + "-" + ret.day);
                        if (!stratTime) {
                            $toast('请先选择开始日期!');
                            return false;
                        }
                        // console.log(ret.year + "-" + ret.month + "-" + ret.day);
                        if (that.compareDate(ret.year + "-" + ret.month + "-" + ret.day, stratTime)) {
                            $toast('出差结束日期需大于出发日期!');
                            return false;
                        }
                    } else{
                        $('#my-endDate').val('');
                    }
                    // console.log(deviceType());
                    if (api.systemType !== 'ios') {
                        if (that.compareDate(ret.year + "-" + ret.month + "-" + ret.day, minDate)) {
                            $toast('请选择正确时间!');
                            return false;
                        }
                    }
                    _this.val(ret.year + "-" + ret.month + "-" + ret.day);
                });
            });
        }

        //step06:选择出行人
        ,picker1Select : function () {
            var that = this;
            var data1 = that.params.data1;
            var picker1El = document.getElementById('picker1');
            var picker1 = new Picker({
                data: [data1]
            });

            picker1.on('picker.select', function(selectedVal, selectedIndex) {
                if ($.inArray(selectedVal.toString(),that.params.ids) != -1) {
                  $alert(data1[selectedIndex[0]].text+'  已经存在，请重新选择');
                  return false;
                }
                //选择出行人
                if ($("#travel_person .u_div").length > 4) {
                    $toast('最多5个');
                    return false;
                }
                var interText = doT.template($("#person_tpl").text());
                $("#travel_person").append(interText({
                    'text': data1[selectedIndex[0]].text,
                    'val': selectedVal
                }));
                that.params.ids.push(selectedVal.toString());
            });
            picker1El.addEventListener('click', function() {
                picker1.show(function() {
                    picker1.refill([data1]);
                });
            });
        }

        //step07:删除出行人
        , delTravelPersonAddEvent : function () {
            var that = this;
            var data1 = that.params.data1;

            $('body').on('click', '.icon-shanchu', function () {
                var temp = [];
                temp.value = $(this).parent().attr('data-val');
                temp.text = $(this).parent().find('.u_name').text();
                // data1.push(temp);
                that.params.ids.splice($.inArray(temp.value,that.params.ids),1);
                $(this).parent().remove();
            });
        }

        //step08:选择审批人
        , picker2Select : function () {
            var that = this;

            var data2 = that.params.data2;
            var picker2El = document.getElementById('picker2');
            var picker2 = new Picker({
                data: [data2]
            });
            picker2.on('picker.select', function(selectedVal, selectedIndex) {
              if ($.inArray(selectedVal.toString(),that.params.approve_ids) != -1) {
                $alert(data2[selectedIndex[0]].text+'  已经存在，请重新选择');
                return false;
              }
                //选择审批人
                var interText = doT.template($("#person_tpl2").text());

                // console.log(JSON.stringify(data2));
                $("#approve_person").append(interText({
                    'text': data2[selectedIndex[0]].text,
                    'val': selectedVal
                }));
                that.params.approve_ids.push(selectedVal.toString());
                // data2.splice(selectedIndex[0], 1);
            });
            picker2El.addEventListener('click', function() {
                picker2.show(function() {
                    picker2.refill([data2]);
                });
            });
        }

        //step09:删除审批人
        , delApprovePersonAddEvent : function () {
            var that = this;
            //审批人删除操作
            $('body').on('click', '.del_approve_person', function () {
                var temp = [];
                temp.value = $(this).parent().attr('data-val');
                temp.text = $(this).parent().find('.u_name').text();
                // that.params.data2.push(temp);
                that.params.approve_ids.splice($.inArray(temp.value,that.params.approve_ids),1);
                $(this).parent().remove();
            });
        }

        //step10:提交申请单数据，包括step11
        , submitApply : function () {
            var that = this;
            $('body').on('click', '#submitApply', function () {
                //step1:验证数据
                if (!that.submitValidate()) {
                    return false;
                }
                //step2:获取出行人员
                var travel_person = '';
                $("#travel_person .u_div").each(function() {
                    travel_person += $(this).attr('data-val') + ',';
                });
                travel_person = travel_person.substring(0, travel_person.length - 1)

                //step3:获取审批人员
                var approve_person = '';
                $("#approve_person .u_div").each(function() {
                    approve_person += $(this).attr('data-val') + ',';
                });
                approve_person = approve_person.substring(0, approve_person.length - 1)

                //step4:获取图片
                var img_url = [];
                $('.img_div img').each(function(){
                    var imgObj = {
                        'src': $(this).attr('src')
                    };
                    img_url.push(imgObj);
                });
                //step5:参数整合
                var param = {};
                param.url = Config.travel.addApply;
                param.data = {
                    'travel_site'       : $("#travel_site").val(),          //出差始发地
                    'travel_destination': $("#travel_destination").val(),   //出差目的地
                    'travel_time'       : $("#my-startDate").val(),         //出差开始时间
                    'travel_end_time'   : $("#my-endDate").val(),           //出差结束时间
                    'business_traveler' : travel_person,                    //出行人员
                    'travel_cause'      : $("#travel_reason").val(),        //出差原因
                    'travel_approver'   : approve_person,                   //审核人员
                    'img_url'           : img_url                           //图片
                    //,'XDEBUG_SESSION_START' : 'PHPSTORM'
                };
                //step6:请求申请单列表接口
                ajax (param, function(ret) {
                    if (ret.code === 1) {
                        $alert('申请成功', function() {
                            api.openWin({
                                name: 'travel_apply_order_win',
                                url: 'travel_apply_order_win.html',
                                pageParam : {
                                    flag : 'add'
                                },
                                slidBackEnabled: false
                            });
                        });
                    } else {
                        $toast('申请失败');
                    }
                })
            });
        }

        //step11:提交参数验证
        , submitValidate : function () {
            if (!$("#travel_site").val()) {
                $toast('请填写始发地');
                return false;
            }
            if (!$("#travel_destination").val()) {
                $toast('请填写始发地');
                return false;
            }
            if (!$('#my-startDate').val()) {
                $toast('请填写出行开始日期');
                return false;
            }
            if (!$('#my-endDate').val()) {
                $toast('请填写出行结束日期');
                return false;
            }
            if ($("#travel_person .u_div").length === 0) {
                $toast('请选择出行人');
                return false;
            }
            if ($("#travel_reason").val() == '') {
                $toast('请填写出差原因');
                return false;
            }
            if ($("#approve_person .u_div").length === 0) {
                $toast('请选择审批人');
                return false;
            }
            return true;
        }

        //step12:重置
        , resetForm : function () {
            $('#reset').click(function () {
                window.location.reload();
            });
        }

        // 工具1:数据结构生成
        , createList : function (obj, list) {
            var arr = Object.keys(obj);
            for (var i = 0; i < arr.length; i++) {
                var k = arr[i];
                var temp = [];
                temp.text = obj[k].user_name;
                temp.value = obj[k].user_id;
                list.push(temp);
            }
            return list;
        }

        //工具2:函数:扩展
        , extend: function (a, b) {
            for (var key in b) {
                if (b.hasOwnProperty(key)) {
                    a[key] = b[key];
                }
            }
            return a;
        }

        //好像没用，不知道是什么
        , seleClick : function () {
            $('.sele_click').click(function() {
                var right = $('#sel_right').css('display');
                if (right === 'none') {
                    $('#sel_right').css('display', 'block');
                    $('#sel_dow').css('display', 'none');
                } else {
                    $('#sel_right').css('display', 'none');
                    $('#sel_dow').css('display', 'block');
                }
            })
        }

        //获取当前时间，格式YYYY-MM-DD
        ,getNowFormatDate: function () {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            return year + seperator1 + month + seperator1 + strDate;
        }

        // 比较时间，格式YYYY-MM-DD
        ,compareDate: function  (d1,d2) {
            let arrayD1 = d1.split("-");
            let date1 = new Date(arrayD1[0],arrayD1[1],arrayD1[2]);
            let arrayD2 = d2.split("-");
            let date2 = new Date(arrayD2[0],arrayD2[1],arrayD2[2]);
            //8/26 8/27
            if (date1 >= date2) {
                return false;
            }
            return true;
        }

        //step17:上传图片
        ,uploadImg :function () {
            var that = this;
            var toast = new auiToast();

            $('body').on('change', '.upload_img', function () {
                var self = $(this);
                var img_num = self.parent().siblings('.img-div').find('img').length;
                if (img_num >= 5) {
                    toast.custom({
                        title: "最多五张图片",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                    return false;
                }
                var file = self[0].files[0];
                if (file) {
                    // 验证文件类型
                    var mime = file.type;
                    var allow_type = ['image/jpeg', 'image/gif', 'image/png', 'image/bmp'];
                    if (allow_type.indexOf(mime) === -1) {
                        alert("请确保文件为图像类型");
                        return false;
                    }
                    // 图片预览
                    var reader = new FileReader();

                    reader.readAsDataURL(file);
                    reader.onload = function() {
                        var interText = doT.template($("#img_tpl").text());
                        self.parent().after(interText(reader.result));
                        var img = new Image();
                        img.src = reader.result.toString();
                        img.onload = function() {
                            //压缩图片
                            var square = 500;
                            var canvas = document.createElement('canvas');
                            canvas.width = square;
                            canvas.height = square;
                            var context = canvas.getContext('2d');
                            context.clearRect(0, 0, square, square);
                            var imageWidth;
                            var imageHeight;
                            var offsetX = 0;
                            var offsetY = 0;
                            //获取图片的宽高
                            if (img.width > img.height) {
                                imageWidth = Math.round(square * img.width / img.height);
                                imageHeight = square;
                                offsetX = -Math.round((imageWidth - square) / 2);
                            } else {
                                imageHeight = Math.round(square * img.height / img.width);
                                imageWidth = square;
                                offsetY = -Math.round((imageHeight - square) / 2);
                            }
                            context.drawImage(img, offsetX, offsetY, imageWidth, imageHeight);
                            var imgData = canvas.toDataURL('image/jpeg');
                            var param = {};
                            param.url = Config.travel.uploadImg;
                            param.data = {
                                imgData: imgData
                            };
                            ajax(param, function(ret) {
                                if (ret.code === 1) {
                                    self.parent().next().find('img').attr('src', ret.data.url_path);
                                } else {
                                    toast.custom({
                                        title: ret.msg,
                                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                                        duration: 2000
                                    });
                                    self.parent().prev().remove();
                                }
                            })
                        };
                    }
                    //onload/end
                }
                //file/end

            });
        }

        //step18:图片删除操作
        ,imageDelete: function () {
            $('body').on('click', '.delete', function () {
                $(this).parent().parent().remove();
            });
        }
    };
    window.applyAdd = applyAdd;
})(window);
